import React, { Component } from 'react';

import './index.css';
import FormUtils from '../../utils/Form';
import { SMS_SEND, PICTURE_CODE,LOGIN } from '../../constants/Api';
import { POST } from '../../utils/Request';
import Toast from '../../components/toast';
let currentTime;
class Index extends Component {
  constructor(props) {
    super(props);
    this.state = {
      msgCode: '',
      phoneNum: '',
      errorText: '',
      msgText: '获取',
      msgWaiting: false,
      modalVisible: false,
      random: '',
      base64Image: '',
      imageCode: '',
      channel: '',
      systems: '',
    }


  };
  componentDidMount() {
    console.log("search:"+JSON.stringify(this.props.location.search))
    let channel = this.props.location.search;
    let ua = navigator.userAgent;
    console.log("ua:"+ua)
    if (!channel) {
      channel = '';
    } else {
      var len = channel.length;
      var noWn = channel.substring(1, len);
      var items = noWn.split('&');
      for (var i = 0; i < items.length; i++) {
        if (items[i].indexOf("channel=") > -1) {
          var itAyyay = items[i].split("=")
          channel = itAyyay[1];
        }
      }
    }
    //处理系统
    let systems;
    if (ua.indexOf('Android') > 0) {
      systems = 'Android';
    } else if (ua.indexOf('iPhone') > 0 || ua.indexOf('iPad') > 0) {
      systems = 'iOS';
    } else {
      systems = 'ohter'
    }
    this.setState({
      channel: channel,
      systems: systems,
    })

  }

  //倒计时
  timeCounter = (seconds, loop) => {
    if (!loop) {
      currentTime = parseInt(new Date().getTime() / 1000);
    }
    let codetime =
      seconds * 1 + currentTime - parseInt(new Date().getTime() / 1000);
    if (codetime <= 0) {
      this.setState({
        msgWaiting: false,
        msgText: '获取',
      });
      return;
    } else {
      this.setState({
        msgWaiting: true,
        msgText: `${codetime}`,
      });
    }
    this.timer = setTimeout(() => {
      this.timeCounter(seconds, true);
    }, 1000);
  };

  closeToast() {
    setTimeout(() => {
      this.setState({
        errorText: ''
      })
    }, 2000)
  }
  toast(text) {
    this.setState({
      errorText: text
    })
    this.closeToast();
  }

  getMsgCode() {
    if (!this.state.phoneNum) {
      this.toast(FormUtils.phone.placeholder)
      return false;
    }
    if (!FormUtils['phone'].reg.test(this.state.phoneNum)) {
      this.toast(FormUtils.phone.errorText)
      return false;
    }
    const params = {
      phone: this.state.phoneNum,
    };
    POST(PICTURE_CODE, params).then(res => {
      if (res.code == 200) {
        POST(SMS_SEND, params).then(data => {
          if (data.code == 200) {
            this.timeCounter(60);
            this.toast(data.msg);
          } else {
            this.setState({
              msgWaiting: false,
            });
            this.toast(data.msg);
          }
        });
      } else if (res.code == 4014) {
        //显示图型验证码
        this.setState({ modalVisible: true });
        let baseImg = `data:image/png;base64,${res.data.image}`;
        this.setState({ base64Image: baseImg, random: res.data.random });
      } else {
        this.setState({
          msgWaiting: false,
        });
        this.toast(res.msg);

      }
    });

  }

  nextHandle() {
    //注册
    if (!this.state.phoneNum) {
      this.toast(FormUtils.phone.placeholder)
      return false;
    }
    if (!FormUtils['phone'].reg.test(this.state.phoneNum)) {
      this.toast(FormUtils.phone.errorText)
      return false;
    }
    if (!this.state.msgCode) {
      this.toast(FormUtils.code.placeholder)
      return false;
    }
    if (!FormUtils['code'].reg.test(this.state.msgCode)) {
      this.toast(FormUtils.code.errorText)
      return false;
    }

    const params = {
      phone: this.state.phoneNum,
      code: this.state.msgCode,
      phoneOs: this.state.systems,
      channel: this.state.channel
    };
    // const { dispatch } = this.props;
    // dispatch(LOGIN_REDUX(params));
    POST(LOGIN, params).then(res => {
      if (res.code == 200) {
        const items = res.data;
      
        this.toast('恭喜您注册成功');
        this.props.history.push('download')
    
      } else {
        this.toast(res.msg);
      }
    });
  
  }
  confirm() {
    if (!this.state.imageCode) {
      alert("请输入图形验证码")
      return false;
    }
    this.setState({
      modalVisible: false
    })
    const params = {
      phone: this.state.phoneNum,
      random: this.state.random,
      code: this.state.imageCode,
    };
    POST(SMS_SEND, params).then(data => {
      // console.log(JSON.stringify(res));
      if (data.code == 200) {
        this.timeCounter(60);
        this.toast(data.msg);
      } else {
        this.toast(data.msg);
      }
    });
  }

  render() {
    return (
      <div className="mainContent">
        <Toast
          text={this.state.errorText}
        />
        <img src={require('../../assets/images/bannar_downloadLand.png')} alt="" className="banner" />
        <div className="forms">
          <div className="formItem">
            <input type="tel" id="inPhone" className="inForm" placeholder="请输入手机号码" maxLength="11" onChange={(e) => {
              this.setState({ phoneNum: e.target.value })
            }} />
          </div>
          <div className="formItem">
            <input type="tel" id="inMsgCode" className="inForm" placeholder="短信验证码" maxLength="8" onChange={(e) => {
              this.setState({ msgCode: e.target.value })
            }} />
            {
              this.state.msgWaiting ?
                <div className="msgCode">{this.state.msgText}</div>
                :
                <div className="msgCode" onClick={() => {
                  this.getMsgCode();
                }}>{this.state.msgText}</div>
            }

          </div>
        </div>
        {/* <div className="next" onClick="_czc.push(['_trackEvent','下载落地页','注册登录','','','']);">申请拿钱</div> */}
        <div className="next" onClick={() => {
          this.nextHandle()
        }} >申请拿钱</div>
        {
          this.state.modalVisible ?
            <div className="popup">
              <div className="popupItem">
                <div className="title">请输入图形验证码</div>
                <div className="line">
                  <input type="text" className="inPicCode" maxLength="5" onChange={(e) => {
                    this.setState({ imageCode: e.target.value })
                  }} />
                  <div onClick={() => {
                    this.getMsgCode()
                  }}>
                    <img src={this.state.base64Image} alt="图形验证码" className="picCode" />
                  </div>
                </div>
                <div className="buttons">
                  <div className="buttonItem" onClick={() => {
                    this.setState({
                      modalVisible: false
                    })
                  }}>取消</div>
                  <div className="buttonItem confirmButton" onClick={() => {
                    this.confirm()
                  }}>确认</div>
                </div>
              </div>
            </div>
            :
            null
        }

      </div>
    );
  }
}

export default Index;
